import { query } from '../../config/db.js';

/**
 * 用户数据模型
 */
export class User {
  constructor(userData) {
    this.id = userData.id;
    this.username = userData.username;
    this.email = userData.email;
    this.password_hash = userData.password_hash;
    this.phone_number = userData.phone_number;
    this.created_at = userData.created_at;
    this.updated_at = userData.updated_at;
  }

  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Promise<Object>} 创建的用户信息
   */
  static async create(userData) {
    const { username, email, password_hash, phone_number } = userData;
    
    const sql = `
      INSERT INTO users (username, email, password_hash, phone_number)
      VALUES (?, ?, ?, ?)
    `;
    
    try {
      const result = await query(sql, [username, email, password_hash, phone_number]);
      
      // 返回新创建的用户信息（不包含密码）
      const newUser = await User.findById(result.insertId);
      return newUser;
    } catch (error) {
      console.error('创建用户失败:', error);
      throw error;
    }
  }

  /**
   * 根据ID查找用户
   * @param {number} id - 用户ID
   * @returns {Promise<Object|null>} 用户信息或null
   */
  static async findById(id) {
    const sql = `
      SELECT id, username, email, phone_number, created_at, updated_at
      FROM users 
      WHERE id = ?
    `;
    
    try {
      const results = await query(sql, [id]);
      return results.length > 0 ? new User(results[0]) : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 根据邮箱查找用户
   * @param {string} email - 邮箱地址
   * @returns {Promise<Object|null>} 用户信息或null
   */
  static async findByEmail(email) {
    const sql = `
      SELECT id, username, email, phone_number, created_at, updated_at
      FROM users 
      WHERE email = ?
    `;
    
    try {
      const results = await query(sql, [email]);
      return results.length > 0 ? new User(results[0]) : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 根据邮箱查找用户（包含密码哈希，用于登录验证）
   * @param {string} email - 邮箱地址
   * @returns {Promise<Object|null>} 用户信息或null
   */
  static async findByEmailWithPassword(email) {
    const sql = `
      SELECT id, username, email, password_hash, phone_number, created_at, updated_at
      FROM users 
      WHERE email = ?
    `;
    
    try {
      const results = await query(sql, [email]);
      return results.length > 0 ? results[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 根据用户名查找用户
   * @param {string} username - 用户名
   * @returns {Promise<Object|null>} 用户信息或null
   */
  static async findByUsername(username) {
    const sql = `
      SELECT id, username, email, phone_number, created_at, updated_at
      FROM users 
      WHERE username = ?
    `;
    
    try {
      const results = await query(sql, [username]);
      return results.length > 0 ? new User(results[0]) : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw error;
    }
  }

  /**
   * 检查邮箱是否已存在
   * @param {string} email - 邮箱地址
   * @returns {Promise<boolean>} 是否存在
   */
  static async emailExists(email) {
    const sql = 'SELECT COUNT(*) as count FROM users WHERE email = ?';
    
    try {
      const results = await query(sql, [email]);
      return results[0].count > 0;
    } catch (error) {
      console.error('检查邮箱失败:', error);
      throw error;
    }
  }

  /**
   * 检查用户名是否已存在
   * @param {string} username - 用户名
   * @returns {Promise<boolean>} 是否存在
   */
  static async usernameExists(username) {
    const sql = 'SELECT COUNT(*) as count FROM users WHERE username = ?';
    
    try {
      const results = await query(sql, [username]);
      return results[0].count > 0;
    } catch (error) {
      console.error('检查用户名失败:', error);
      throw error;
    }
  }

  /**
   * 更新用户信息
   * @param {number} id - 用户ID
   * @param {Object} updateData - 要更新的数据
   * @returns {Promise<Object|null>} 更新后的用户信息
   */
  static async update(id, updateData) {
    const allowedFields = ['username', 'email', 'phone_number'];
    const updateFields = [];
    const updateValues = [];

    // 只允许更新指定字段
    for (const field of allowedFields) {
      if (updateData[field] !== undefined) {
        updateFields.push(`${field} = ?`);
        updateValues.push(updateData[field]);
      }
    }

    if (updateFields.length === 0) {
      throw new Error('没有可更新的字段');
    }

    updateValues.push(id);
    const sql = `
      UPDATE users 
      SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    try {
      await query(sql, updateValues);
      return await User.findById(id);
    } catch (error) {
      console.error('更新用户失败:', error);
      throw error;
    }
  }

  /**
   * 更新用户密码
   * @param {number} id - 用户ID
   * @param {string} newPasswordHash - 新密码哈希
   * @returns {Promise<boolean>} 是否更新成功
   */
  static async updatePassword(id, newPasswordHash) {
    const sql = `
      UPDATE users 
      SET password_hash = ?, updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    try {
      const result = await query(sql, [newPasswordHash, id]);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新密码失败:', error);
      throw error;
    }
  }

  /**
   * 删除用户
   * @param {number} id - 用户ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  static async delete(id) {
    const sql = 'DELETE FROM users WHERE id = ?';
    
    try {
      const result = await query(sql, [id]);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('删除用户失败:', error);
      throw error;
    }
  }

  /**
   * 获取用户统计信息
   * @returns {Promise<Object>} 统计信息
   */
  static async getStats() {
    const sql = `
      SELECT 
        COUNT(*) as total_users,
        COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as today_registrations,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as week_registrations,
        COUNT(CASE WHEN created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) as month_registrations
      FROM users
    `;

    try {
      const results = await query(sql);
      return results[0];
    } catch (error) {
      console.error('获取用户统计失败:', error);
      throw error;
    }
  }

  /**
   * 转换为安全的JSON格式（不包含敏感信息）
   * @returns {Object} 安全的用户信息
   */
  toSafeJSON() {
    return {
      id: this.id,
      username: this.username,
      email: this.email,
      phone_number: this.phone_number,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}
